package biznussoft.metercor.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import biznussoft.metercor.AccountsActivity;
import biznussoft.metercor.MainActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.entity.AccountModel;
import biznussoft.metercor.entity.ContactsModel;
import biznussoft.metercor.listener.Globallistener;
import biznussoft.metercor.lookup.AccountLookup;
import biznussoft.metercor.utils.Session;

import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class ContactDetailsFragment  extends Fragment implements OnClickListener,OnTouchListener {

	public static EditText etContactAccountName;
	private EditText etMaillingCity,etMaillingStreet,etMailingCountry,etMaillingstate,etMaillingZip,etOtherCity,etOtherStreet,etOtherState,etOtherCountry,etOtherZip,etFirstName,etLastName,etTitle,etContactphone,etMobile,etEmail,etDescription;
	private TextView  tvContactBillingToShipping,tvMaillingCity,tvMaillingStreet,tvMailingCountry,tvMaillingstate,tvMaillingZip,tvContactAccountName,tvOtherCity,tvOtherStreet,tvOtherState,tvOtherCountry,tvOtherZip,
	tvFirstName,tvLastName,tvTitle,tvContactphone,tvMobile,tvEmail,tvDescription,tvAccountName;
	private RestClient client;
	private ImageView mContactSave,mCancel;
	private Spinner mType,mIndustry,etLeadSource;
	private Bundle args2;
	private String parantAccountID;
	static ArrayList<ContactsModel> contactList;
	private ContactsModel model;
	private boolean flag;
	private Globallistener mHomeItemListener;   
	private MenuItem edit,logout;
	private int mPosition ;
	private String mCategory;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.contact_details_fragment, null);
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mHomeItemListener = (Globallistener) (activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setHasOptionsMenu(true);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);

		mContactSave = (ImageView) getView().findViewById(R.id.btSave2);
		mCancel = (ImageView) getView().findViewById(R.id.btCancel2);
		mType = (Spinner) getView().findViewById(R.id.etType);
		mIndustry = (Spinner) getView().findViewById(R.id.etIndustry);
		tvContactBillingToShipping = (TextView)getView().findViewById(R.id.tvCopyContactBillingToShipping);


		tvContactBillingToShipping.setOnClickListener(this);
		mContactSave.setOnClickListener(this);    
		mCancel.setOnClickListener(this);

		etMailingCountry = (EditText) getView().findViewById(R.id.etMailingcountry);
		etMaillingCity = (EditText) getView().findViewById(R.id.etMailingcity);
		etMaillingstate = (EditText) getView().findViewById(R.id.etMailingState);
		etMaillingStreet = (EditText) getView().findViewById(R.id.etMailingStreet);
		etMaillingZip = (EditText) getView().findViewById(R.id.etMailingcode);
		etContactAccountName = (EditText) getView().findViewById(R.id.etContactAccountName);
		etContactAccountName.setOnTouchListener(this);
		etContactAccountName.setText(Session.sAccountName);                      
		etOtherCity = (EditText) getView().findViewById(R.id.etOtherCity);
		etOtherCountry = (EditText) getView().findViewById(R.id.etOthercountry);
		etOtherState = (EditText) getView().findViewById(R.id.etOtherState);
		etOtherStreet = (EditText) getView().findViewById(R.id.etOtherstreet);
		etOtherZip = (EditText) getView().findViewById(R.id.etOthercode);
		etFirstName = (EditText) getView().findViewById(R.id.etFirstname);
		etLastName = (EditText) getView().findViewById(R.id.etLastname);
		etTitle = (EditText) getView().findViewById(R.id.etTite);
		etMobile = (EditText) getView().findViewById(R.id.etMobile);
		etEmail = (EditText) getView().findViewById(R.id.etEmail);
		etContactphone = (EditText) getView().findViewById(R.id.etContactPhone);
		etLeadSource = (Spinner) getView().findViewById(R.id.etLeadSource);
		etDescription = (EditText) getView().findViewById(R.id.etDescription);


	
		tvEmail = (TextView) getView().findViewById(R.id.tvEmail);
		tvContactphone = (TextView) getView().findViewById(R.id.tvContactPhone);


		client = MainActivity.mActivity.client;


		/* args2 = getArguments();
		 if (args2 != null) {                 


			 if(args2.getInt("Position")== 1){
				 svContactdetails.setVisibility(View.VISIBLE);
				 svContact.setVisibility(View.GONE);
				 parantAccountID =args2.getString("AccountId");

			 }else{
				 svContact.setVisibility(View.VISIBLE);
				 svContactdetails.setVisibility(View.GONE);
				 etMailingCountry.setText(args2.getString("MailingCountry"));
				 etMaillingCity.setText(args2.getString("MaillingCity"));
				 etMaillingstate.setText(args2.getString("Maillingstate"));
				 etMaillingStreet.setText(args2.getString("MaillingStreet"));
				 etMaillingZip.setText(args2.getString("MaillingZip"));
				 etContactphone.setText(args2.getString("Contactphone"));
				 etContactAccountName.setText(args2.getString("ContactAccountName"));
				 parantAccountID = args2.getString("AccountId");
			 }


		 }*/

	}


	public void showContacts(int position,String category){

		mPosition = position;
		mCategory = category;

		model = AccountDetailsFragment.contactList.get(position);

		tvAccountName.setText(Session.sAccountName);                    
		tvLastName.setText(model.getLastName());           
		tvFirstName.setText(model.getFirstName());
		tvContactphone.setText(model.getPhone());
		tvMaillingCity.setText(model.getMailingCity());
		tvMailingCountry.setText(model.getMailingCountry());
		tvMaillingZip.setText(model.getMailingPostalCode());
		tvMaillingstate.setText(model.getMailingState());
		tvMaillingStreet.setText(model.getMailingStreet());
		tvOtherCity.setText(model.getOtherCity());
		tvOtherCountry.setText(model.getOtherCountry());
		tvOtherZip.setText(model.getOtherPostalCode());      
		tvOtherState.setText(model.getOtherState());
		tvOtherStreet.setText(model.getOtherStreet());
		tvEmail.setText(model.getEmail());
		tvMobile.setText(model.getMobilePhone());   
		tvTitle.setText(model.getTitle());

		parantAccountID =model.getId();


	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {          


		case R.id.btSave2:
			if (!flag) {
				createContact();
			} else {
				updateContact(parantAccountID);
			}
			break;

		case R.id.tvCopyContactBillingToShipping:
			String MaillingCity = etMaillingCity.getText().toString();
			if (MaillingCity != null) {
				etOtherCity.setText(MaillingCity);
			}
			String MailingCountry = etMailingCountry.getText().toString();
			if (MailingCountry != null) {
				etOtherCountry.setText(MailingCountry);
			}

			String MailingZip = etMaillingZip.getText().toString();
			if (MailingZip != null) {
				etOtherZip.setText(MailingZip);
			}
			String MailingState = etMaillingstate.getText().toString();
			if (MailingState != null) {
				etOtherState.setText(MailingState);
			}
			String MailingStreet = etMaillingStreet.getText().toString();
			if (MailingStreet != null) {
				etOtherStreet.setText(MailingStreet);
			}

			break;

		case R.id.btCancel2:
			break;
		default:
			break;
		}
	}

	public void editAccount(){
		flag = true; 
		etLastName.setText(model.getLastName());           
		etFirstName.setText(model.getFirstName());
		etContactphone.setText(model.getPhone());
		etMaillingCity.setText(model.getMailingCity());
		etMailingCountry.setText(model.getMailingCountry());
		etMaillingZip.setText(model.getMailingPostalCode());
		etMaillingstate.setText(model.getMailingState());
		etMaillingStreet.setText(model.getMailingStreet());
		etOtherCity.setText(model.getOtherCity());
		etOtherCountry.setText(model.getOtherCountry());
		etOtherZip.setText(model.getOtherPostalCode());      
		etOtherState.setText(model.getOtherState());
		etOtherStreet.setText(model.getOtherStreet());
		etEmail.setText(model.getEmail());
		etMobile.setText(model.getMobilePhone());   
		etTitle.setText(model.getTitle());

	}
	
	boolean checkEmailCorrect(String Email) {
        String pttn = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
        Pattern p = Pattern.compile(pttn);
        Matcher m = p.matcher(Email);

        if (m.matches()) {
               return true;
        }
        return false;
 }

	public void createContact(){
		{

			if(etLastName.getText().toString().trim().length()>0){

				if(checkEmailCorrect(etEmail.getText().toString().trim())){
					String objectType = "Contact";
					HashMap<String, Object> fields = new HashMap<String, Object>();

					/*
					 * change the parent ID to Account id
					 */
					fields.put("AccountId",Session.sParentId);
					fields.put("FirstName",etFirstName.getText().toString());
					fields.put("LastName",etLastName.getText().toString());
					fields.put("Phone",etContactphone.getText().toString());
					fields.put("MailingCity",etMaillingCity.getText().toString());
					fields.put("MailingState",etMaillingstate.getText().toString());
					fields.put("MailingCountry", etMailingCountry.getText().toString());
					fields.put("MailingPostalCode", etMaillingZip.getText().toString());
					fields.put("MailingStreet", etMaillingStreet.getText().toString());
					fields.put("OtherCity", etOtherCity.getText().toString());
					fields.put("OtherCountry",etOtherCountry.getText().toString());
					fields.put("OtherPostalCode",etOtherZip.getText().toString());
					fields.put("OtherState",etOtherState.getText().toString());
					fields.put("OtherStreet",etOtherStreet.getText().toString());
					fields.put("Email",etEmail.getText().toString());
					fields.put("MobilePhone",etMobile.getText().toString());
					fields.put("Title",etTitle.getText().toString());
					fields.put("LeadSource", etLeadSource.getSelectedItem().toString());
					fields.put("Description", etDescription.getText().toString());
					Log.i("NCS","Request   is :"+fields);
					try {
						RestRequest restRequest = RestRequest.getRequestForCreate(AccountModel.api_Version,objectType,fields);

						Log.i("NCS","Service   is :"+fields);
						client.sendAsync(restRequest, new AsyncRequestCallback() {
							@Override
							public void onSuccess(RestRequest request, RestResponse result) {
								try {     
									Log.i("NCS","Result  is :"+result);

									startActivity(new Intent(getActivity(),AccountsActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
									JSONObject json = new JSONObject(result.toString());
									if(json!= null){
										if(json.getString("success").equalsIgnoreCase("true")){

										}

									}


								}                                
								catch (Exception exception) {

								}
							}

							//@Override
							public void onError(Exception exception) {
								Toast.makeText(getActivity(),
										ContactDetailsFragment.this.getString(SalesforceSDKManager.getInstance().getSalesforceR().stringGenericError(), exception.toString()),
										Toast.LENGTH_LONG).show();
								EventsObservable.get().notifyEvent(EventType.RenditionComplete);
							}
						});             
					} 
					catch (Exception e) {
						Log.i("NCS","Exception is   :"+e.getMessage());

					}
				}else{
					Toast.makeText(getActivity(), "Please enter a vaild email", 1000).show();
				}
			}else{
				Toast.makeText(getActivity(), "Please enter LastName", 1000).show();
			}
		}


	}

	public void updateContact(String id){
		{

			String objectType = "Contact";
			HashMap<String, Object> fields = new HashMap<String, Object>();
			fields.put("AccountId",Session.sParentId);
			fields.put("FirstName",etFirstName.getText().toString());
			fields.put("LastName",etLastName.getText().toString());
			fields.put("Phone",etContactphone.getText().toString());
			fields.put("MailingCity",etMaillingCity.getText().toString());
			fields.put("MailingState",etMaillingstate.getText().toString());
			fields.put("MailingCountry", etMailingCountry.getText().toString());
			fields.put("MailingPostalCode", etMaillingZip.getText().toString());
			fields.put("MailingStreet", etMaillingStreet.getText().toString());
			fields.put("OtherCity", etOtherCity.getText().toString());
			fields.put("OtherCountry",etOtherCountry.getText().toString());
			fields.put("OtherPostalCode",etOtherZip.getText().toString());
			fields.put("OtherState",etOtherState.getText().toString());
			fields.put("OtherStreet",etOtherStreet.getText().toString());
			fields.put("Email",etEmail.getText().toString());
			fields.put("MobilePhone",etMobile.getText().toString());
			fields.put("Title",etTitle.getText().toString());
			fields.put("LeadSource", etLeadSource.getSelectedItem().toString());
			fields.put("Description", etDescription.getText().toString());

			try {
				RestRequest restRequest = RestRequest.getRequestForUpdate(AccountModel.api_Version,objectType,id,fields);


				client.sendAsync(restRequest, new AsyncRequestCallback() {
					@Override
					public void onSuccess(RestRequest request, RestResponse result) {
						try {     
							showContacts(mPosition,mCategory);
							JSONObject json = new JSONObject(result.toString());
							if(json!= null){
								if(json.getString("success").equalsIgnoreCase("true")){
									mHomeItemListener.onCategoryClicked(-2);
								}

							}


						}                                
						catch (Exception exception) {

						}
					}

					//@Override
					public void onError(Exception exception) {
						Toast.makeText(getActivity(),
								ContactDetailsFragment.this.getString(SalesforceSDKManager.getInstance().getSalesforceR().stringGenericError(), exception.toString()),
								Toast.LENGTH_LONG).show();
						EventsObservable.get().notifyEvent(EventType.RenditionComplete);
					}
				});
			} 
			catch (Exception e) {
				Log.i("NCS","Exception is   :"+e.getMessage());

			}

		}


	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if(event.getAction() == MotionEvent.ACTION_UP){
			AccountLookup lookup = new AccountLookup();
			lookup.accountLookupDetails(getActivity(),"contact");
		}
		return false;
	}



}
